package net.hserver.apm.plugin.task;

import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Task;
import cn.hserver.core.queue.HServerQueue;
import cn.hserver.core.server.HumClient;
import cn.hserver.core.server.context.ConstConfig;
import cn.hserver.core.server.context.HumMessage;
import cn.hserver.core.server.util.IpUtil;
import cn.hserver.core.server.util.RequestIdGen;
import net.hserver.apm.common.DataConfig;
import net.hserver.apm.common.entity.ServerInfo;

import java.util.Properties;

import static net.hserver.apm.common.DataConfig.APM_DATA_INFO;


@Bean
public class DataTask {

    /**
     * 一分钟一次
     */
    public final static int TIME = 1000 * 60;
    public static Long requestNum = 0L;


    @Task(name = "checkConnect", time = TIME * 5 + "")
    public void connect() {
        HumClient.sendMessage(new HumMessage(DataConfig.APM_CONNECT, ConstConfig.APP_NAME));
    }

    @Task(name = "upload", time = TIME + "")
    public void upload() {
        if (DataConfig.hum != null && DataConfig.hum.isLive()) {
            ServerInfo serverInfo = new ServerInfo();
            serverInfo.setAppName(ConstConfig.APP_NAME);
            serverInfo.setIp(IpUtil.getLocalIP());
            long requestCount = RequestIdGen.getRequestCount();
            serverInfo.setRequestTotal(requestCount);
            serverInfo.setRequestSize(requestCount - requestNum);
            serverInfo.setThreadNum(Thread.currentThread().getThreadGroup().getParent().activeCount());
            serverInfo.setMemoryTotal((int) (Runtime.getRuntime().totalMemory() / 1024 / 1024));
            serverInfo.setMemoryFree((int) (Runtime.getRuntime().freeMemory() / 1024 / 1024));
            Properties properties = System.getProperties();
            serverInfo.setSystemName(properties.getProperty("os.name") + "-" + properties.getProperty("os.version") + "-" + properties.getProperty("os.arch"));
            serverInfo.setTime(System.currentTimeMillis());
            HServerQueue.sendQueue("APM_SEND", APM_DATA_INFO, serverInfo);
            requestNum = requestCount;
        }
    }
}
